<template>
    <div>
        <el-button
            type="primary"
            icon="Plus"
            @click="handleAddTradeMark"
            v-has="`btn.Trademark.add`"
        >
            添加品牌
        </el-button>

        <el-table border class="my_table" :data="data">
            <el-table-column align="center" label="序号" width="80" type="index" />
            <el-table-column align="center" label="品牌名称" prop="tmName" />
            <el-table-column align="center" label="品牌LOGO">
                <template #default="{ row }">
                    <img :src="row.logoUrl" alt="" style="width: 50px; height: 50px" />
                </template>
            </el-table-column>
            <el-table-column align="center" label="品牌操作">
                <template #default="{ row }">
                    <el-button type="primary" size="small" @click="handleEditTradeMark(row)">
                        编辑
                    </el-button>
                    <el-popconfirm
                        width="250px"
                        :title="`您确定要删除品牌${row.tmName}吗？`"
                        @confirm="handleDeleteTradeMark(row)"
                    >
                        <template #reference>
                            <el-button type="danger" size="small">删除</el-button>
                        </template>
                    </el-popconfirm>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[4, 8, 12, 16, 20]"
            background
            layout=" prev, pager, next, jumper,->,total, sizes"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="getTradeMarkList"
        />

        <el-dialog
            v-model="dialogVisible"
            :modal="true"
            :title="tradeMarkParam.id ? '编辑品牌' : '新增品牌'"
            class="dialog"
            width="700px"
        >
            <el-form :model="tradeMarkParam" :rules="rules" ref="tradeMarkForm">
                <el-form-item
                    label="品牌名称"
                    label-width="100px"
                    style="width: 600px"
                    prop="tmName"
                >
                    <el-input placeholder="请输入品牌名称" v-model="tradeMarkParam.tmName" />
                </el-form-item>
                <el-form-item label="品牌LOGO" label-width="100px" prop="logoUrl">
                    <el-upload
                        class="avatar-uploader"
                        action="/api/admin/product/fileUpload"
                        :before-upload="beforeAvatarUpload"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                    >
                        <img
                            v-if="tradeMarkParam.logoUrl"
                            :src="tradeMarkParam.logoUrl"
                            class="avatar"
                        />
                        <el-icon v-else class="avatar-uploader-icon">
                            <Plus />
                        </el-icon>
                    </el-upload>
                </el-form-item>
            </el-form>

            <template #footer>
                <div class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="handleAddTradeMarkSubmit">确定</el-button>
                </div>
            </template>
        </el-dialog>
    </div>
</template>

<script setup lang="ts">
import {
    reqAddOrUpdateTrademark,
    reqDeleteTrademark,
    reqGetTradeMarkList,
} from '@/api/product/tradmark'
import type { Records, TradeMark, TradeMarkResponseData } from '@/api/product/tradmark/type'
import type { UploadProps } from 'element-plus'
import { ElMessage } from 'element-plus'
import { nextTick, onMounted, ref } from 'vue'

let currentPage = ref<number>(1)
let pageSize = ref<number>(8)
let total = ref<number>(0)
let data = ref<Records>([])
let dialogVisible = ref<boolean>(false)
let tradeMarkForm = ref()

let tradeMarkParam = ref<TradeMark>({
    tmName: '',
    logoUrl: '',
})

const validateTmName = (_rule: any, value: any, callback: any) => {
    if (value.trim().length < 2) {
        callback(new Error('品牌名称不能少于2个字符'))
    } else {
        callback()
    }
}

const validateLogoUrl = (_rule: any, value: any, callback: any) => {
    if (value.trim().length === 0) {
        callback(new Error('品牌LOGO不能为空'))
    } else {
        callback()
    }
}

// 表单提交校验
const rules = {
    tmName: { required: true, trigger: 'blur', validator: validateTmName },
    logoUrl: { required: true, trigger: 'blur', validator: validateLogoUrl },
}

// 品牌列表
const getTradeMarkList = async (page: number = 1) => {
    currentPage.value = page
    let res: TradeMarkResponseData = await reqGetTradeMarkList(currentPage.value, pageSize.value)
    if (res.code === 200) {
        total.value = res.data.total
        data.value = res.data.records
    }
}

onMounted(() => {
    getTradeMarkList()
})

// 分页大小改变
const handleSizeChange = () => {
    getTradeMarkList()
}

// 新增品牌
const handleAddTradeMark = () => {
    dialogVisible.value = true

    tradeMarkParam.value.tmName = ''
    tradeMarkParam.value.logoUrl = ''
    tradeMarkParam.value.id = 0

    nextTick(() => {
        tradeMarkForm.value.clearValidate()
    })
}

// 品牌上传前校验
const beforeAvatarUpload: UploadProps['beforeUpload'] = rawFile => {
    if (
        rawFile.type !== 'image/jpeg' &&
        rawFile.type !== 'image/png' &&
        rawFile.type !== 'image/gif'
    ) {
        ElMessage.error('请上传JPG或PNG或GIF格式的图片')
        return false
    } else if (rawFile.size / 1024 / 1024 > 4) {
        ElMessage.error('图片大小不能超过4MB')
        return false
    }
    return true
}

// 品牌上传成功回调
const handleAvatarSuccess: UploadProps['onSuccess'] = response => {
    tradeMarkParam.value.logoUrl = response.data
}

// 新增品牌提交
const handleAddTradeMarkSubmit = async () => {
    await tradeMarkForm.value.validate()

    let result = await reqAddOrUpdateTrademark(tradeMarkParam.value)
    if (result.code === 200) {
        dialogVisible.value = false
        getTradeMarkList()
        let msg = tradeMarkParam.value.id ? '更新品牌成功' : '新增品牌成功'

        ElMessage.success(msg)
    } else {
        let msg = tradeMarkParam.value.id ? '更新品牌失败' : '新增品牌失败'
        dialogVisible.value = false
        ElMessage.error(msg)
    }
}

// 编辑品牌
const handleEditTradeMark = (row: TradeMark) => {
    dialogVisible.value = true
    Object.assign(tradeMarkParam.value, row)

    nextTick(() => {
        tradeMarkForm.value.clearValidate()
    })
}

// 删除品牌
const handleDeleteTradeMark = async (row: TradeMark) => {
    let result = await reqDeleteTrademark(row.id as number)
    if (result === 200) {
        getTradeMarkList(data.value.length > 2 ? currentPage.value : currentPage.value - 1)
        ElMessage.success('删除品牌成功')
    } else {
        ElMessage.error('删除品牌失败')
    }
}
</script>

<style lang="scss" scoped>
.my_table {
    margin: 20px 0;
}

.avatar-uploader .avatar {
    display: block;
    width: 178px;
    height: 178px;
}
</style>
<style>
.avatar-uploader .el-upload {
    position: relative;
    overflow: hidden;
    cursor: pointer;
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    width: 178px;
    height: 178px;
    font-size: 28px;
    color: #8c939d;
    text-align: center;
}
</style>
